using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using System.Collections;
using System.Collections.Generic;

using Microsoft.SharePoint.Utilities;

using ProtocolsFeature;

using System.Diagnostics;
using System.Diagnostics.Eventing;

using iLoveSharePoint.Fields;

namespace ProtocolsFeature.Features.ProtocolsFeature
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("1072fef2-919e-4462-af88-08829ac8bbfd")]
    public class ProtocolsFeatureEventReceiver : SPFeatureReceiver
    {
        // Uncomment the method below to handle the event raised after a feature has been activated.


     
      

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {

            base.FeatureActivated(properties);


            try
            {




                using (SPWeb web = (SPWeb)properties.Feature.Parent)
                {


                web.AllowUnsafeUpdates = true;

                BindLookupToList(web, "IncomingDocuments", "DocumentType", "DocumentTypes");
                BindLookupToList(web, "IncomingDocuments", "DocumentCategory", "DocumentCategory");
                BindLookupToList(web, "IncomingDocuments", "DocumentSubCategory", "DocumentSubCategory");
                // BindLookupToList(web, "IncomingDocuments", "DocumentStatus", "Status");
                BindLookupToList(web, "IncomingDocuments", "OwnerDepartment", "Departments");



                List<string> searchable = new List<string>();

                searchable.Add("Title");
                searchable.Add("FullName");

                BindLookupWithPickerControl(web, "IncomingDocuments", "DocumentSentBy", "ProtocolContacts", searchable, "FullName");
                    

                DisableVersioningOnList(web, "IncomingDocuments");


                BindLookupToList(web, "OutgoingDocuments", "DocumentType", "DocumentTypes");
                BindLookupToList(web, "OutgoingDocuments", "DocumentCategory", "DocumentCategory");
                BindLookupToList(web, "OutgoingDocuments", "DocumentSubCategory", "DocumentSubCategory");
                //BindLookupToList(web, "OutgoingDocuments", "DocumentStatus", "Status");
                BindLookupToList(web, "OutgoingDocuments", "OwnerDepartment", "Departments");




                BindLookupWithPickerControl(web, "OutgoingDocuments", "DocumentRecipient", "ProtocolContacts", searchable, "FullName");



                searchable = new List<string>();

                searchable.Add("Title");
                searchable.Add("ProtocolID");
                BindLookupWithPickerControl(web, "OutgoingDocuments", "OutgoingRelatedDocuments", "OutgoingDocuments", searchable, "Title");
                BindLookupWithPickerControl(web, "OutgoingDocuments", "IncomingRelatedDocuments", "IncomingDocuments", searchable, "Title");
         
                DisableVersioningOnList(web, "OutgoingDocuments");




                web.Update();

                }

            }
            catch (Exception codeException)
            {
                WriteError(codeException);
            }



        }


        public void BindLookupWithPickerControl(SPWeb web, string sourcelistName, string sourcefield, string targetListName, List<string> searchable, string lookupField)
        {

            try
            {


                SPList sourceList = web.GetList(string.Format("{0}/Lists/{1}", web.ServerRelativeUrl, sourcelistName));
                SPList targetList = web.GetList(string.Format("{0}/Lists/{1}", web.ServerRelativeUrl, targetListName));


                //SPFieldLookup field = (SPFieldLookup)web.Fields.GetFieldByInternalName(sourcefield);

               

                LookupFieldWithPicker field = (LookupFieldWithPicker)web.Fields.GetFieldByInternalName(sourcefield);


                // Update the site column
                field.LookupList = targetList.ID.ToString();
                field.LookupWebId = web.ID;
                field.SearchableFields = searchable;
                field.Update();


                field.LookupField = lookupField;


                web.Update();

                // update the list column


                field = (LookupFieldWithPicker)sourceList.Fields.GetFieldByInternalName(sourcefield);


                // field = (SPFieldLookup)sourceList.Fields.GetFieldByInternalName(sourcefield);
                field.LookupList = targetList.ID.ToString();
                field.LookupWebId = web.ID;
                field.SearchableFields = searchable;
                field.LookupField = lookupField;

                field.Update();

                sourceList.Update();
                web.Update();


            }
            catch (Exception codeException)
            {
                WriteError(codeException);
            }



        }



        public void DeleteList(SPWeb web, string listName)
        {

            try
            {
                SPList list =  web.GetList(string.Format("{0}/Lists/{1}", web.ServerRelativeUrl, listName));

                list.Delete();

                web.Update();
            }
            catch (Exception codeException)
            {
                WriteError(codeException);
            }

        }



        public void DeleteSiteColumn(SPWeb web, string FieldName)
        {

            try
            {


                SPField field = web.Fields.TryGetFieldByStaticName(FieldName);
                field.Delete();

                //web.Fields.Delete(FieldName);

                
            }
            catch (Exception codeException)
            {
                WriteError(codeException);
            }




        }



        public void DeleteContentType(SPWeb web, string CTname)
        {

            try
            {

                SPContentType obsolete = web.ContentTypes[CTname];

                // We have a content type.
                if (obsolete != null)
                {
                    //IList<SPContentTypeUsage> usages = SPContentTypeUsage.GetUsages(obsolete);

                    // It is in use.
                    //if (usages.Count <= 0)
                    //{
                        web.ContentTypes.Delete(obsolete.Id);
                    //}
                }

            }
            catch (Exception codeException)
            {
                WriteError(codeException);
            }



        }



        public void DisableVersioningOnList(SPWeb web, string sourcelistName)
        {

            try
            {


                SPList sourceList = web.GetList(string.Format("{0}/Lists/{1}", web.ServerRelativeUrl, sourcelistName));



                sourceList.EnableVersioning = false;
                sourceList.ForceCheckout = false;
              
                sourceList.Update();
                web.Update();


            }
            catch (Exception codeException)
            {
                WriteError(codeException);
            }


        }



     
        
        public void BindLookupToList(SPWeb web, string sourcelistName, string sourcefield, string targetListName)
        {

            try
            {


                SPList sourceList = web.GetList( string.Format("{0}/Lists/{1}", web.ServerRelativeUrl,sourcelistName) );
                SPList targetList =  web.GetList( string.Format("{0}/Lists/{1}", web.ServerRelativeUrl,targetListName) );

               
                SPFieldLookup field = (SPFieldLookup)web.Fields.GetFieldByInternalName(sourcefield);


                // Update the site column
                field.LookupList = targetList.ID.ToString();
                field.LookupWebId = web.ID;
                field.Update();

                web.Update();

               
                // update the list column
                field = (SPFieldLookup)sourceList.Fields.GetFieldByInternalName(sourcefield);
                field.LookupList = targetList.ID.ToString();
                field.LookupWebId = web.ID;
                field.Update();

                sourceList.Update();
                web.Update();


            }
            catch (Exception codeException)
            {
                WriteError(codeException);
            }



        }

        // Uncomment the method below to handle the event raised before a feature is deactivated.

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {


            try
            {


               

                using (SPWeb web = (SPWeb)properties.Feature.Parent)
                {

                web.AllowUnsafeUpdates = true;


                // Remove the lists we created


            
                    
                DeleteList(web, "DocumentTypes");
                DeleteList(web, "DocumentCategory");
                DeleteList(web, "DocumentSubCategory");
                DeleteList(web, "Departments");
      

                DeleteList(web, "ProtocolContacts");

                DeleteList(web, "LibraryConfiguration");

                DeleteList(web, "IncomingDocuments");
                DeleteList(web, "OutgoingDocuments");


                DeleteList(web, "MailMessages");

                    

                    
                // Empty recycle bin so we have no references
                // web.RecycleBin.DeleteAll();

                // Remove the Content Types we created
                DeleteContentType(web, "Department");
                DeleteContentType(web, "DocumentCategory");
                DeleteContentType(web, "DocumentSubCategory");
                DeleteContentType(web, "DocumentType");
                DeleteContentType(web, "LibraryConfiguration");

                DeleteContentType(web, "ProtocolContact");

                DeleteContentType(web, "ProtocolDocument");


                web.Update();


                DeleteSiteColumn(web, "DepartmentManagers");

                DeleteSiteColumn(web, "DocumentApprovers");
                DeleteSiteColumn(web, "ListName");
                DeleteSiteColumn(web, "Router");
                DeleteSiteColumn(web, "Formula");
                DeleteSiteColumn(web, "IDOffset");
                DeleteSiteColumn(web, "ApprovedValue");
                DeleteSiteColumn(web, "ProtocolID");
                DeleteSiteColumn(web, "SubmitterProtocolID");
                DeleteSiteColumn(web, "ReservedProtocolID");
                DeleteSiteColumn(web, "DocumentType");
                DeleteSiteColumn(web, "DocumentCategory");
                DeleteSiteColumn(web, "DocumentSubCategory");
                DeleteSiteColumn(web, "DocumentSubject");
                DeleteSiteColumn(web, "OrganizationType");
                DeleteSiteColumn(web, "Organization");
                DeleteSiteColumn(web, "OwnerDepartment");
                DeleteSiteColumn(web, "DocumentStatus");

                DeleteSiteColumn(web, "IsClosed");
                DeleteSiteColumn(web, "ProtocolRouter");

                DeleteSiteColumn(web, "DocumentRecipient");  

                    





                web.Update();


                }

            }
            catch (Exception codeException)
            {
                WriteError(codeException);
            }


        }



        private void WriteError(Exception ex)
        {

            EventLog LogToSystem = new EventLog();

            LogToSystem.Source = "SharePoint 2010 Protocols Library";
            LogToSystem.WriteEntry(ex.Message + " : " + ex.StackTrace, EventLogEntryType.Error);

        }


        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        //public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        //{
        //}

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
    }
}
